﻿using System.Linq;
using Nop.Core.Data;
using Nop.Plugin.Pricing.PreciousMetals.Domain;
using Nop.Core;
using Nop.Core.Caching;

namespace Nop.Plugin.Pricing.PreciousMetals.Services
{
    public class PreciousMetalsDetailService : IPreciousMetalsDetailService
    {
        private readonly IRepository<PreciousMetalsDetail> _repository;
        private readonly ICacheManager _cacheManager;
        private const string DETAIL_BY_ID_KEY = "pricing.by.id-{0}";

        public PreciousMetalsDetailService(ICacheManager cacheManager, IRepository<PreciousMetalsDetail> repository)
        {
            _cacheManager = cacheManager;
            _repository = repository;
        }

        public IPagedList<PreciousMetalsDetail> GetAll(int pageIndex, int pageSize)
        {
            return new PagedList<PreciousMetalsDetail>(_repository.Table.OrderBy(p => p.ProductVariantId), pageIndex, pageSize);
        }

        public PreciousMetalsDetail Get(int productVariantId)
        {
            string key = string.Format(DETAIL_BY_ID_KEY, productVariantId);

            return _cacheManager.Get(key, () =>
            {
                return this._repository.Table.SingleOrDefault(x => x.ProductVariantId == productVariantId);
            });
        }

        public void Save(PreciousMetalsDetail detail)
        {
            var existing = this.Get(detail.ProductVariantId);
            if (existing == null)
            {
                _repository.Insert(detail);
            }
            else
            {
                detail.Id = existing.Id;
                _repository.Update(detail);
                _cacheManager.Remove(string.Format(string.Format(DETAIL_BY_ID_KEY, detail.ProductVariantId)));
            }
        }

        public void Clear(int productVariantId)
        {
            var existing = this.Get(productVariantId);
            if (existing != null)
            {
                _repository.Delete(existing);
                _cacheManager.Remove(string.Format(string.Format(DETAIL_BY_ID_KEY, productVariantId)));
            }
        }
    }
}